/**
 *
 */

package com.tim.app.share;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.application.library.dialog.LoadingDialog;
import com.application.library.log.DLOG;
import com.application.library.runtime.event.EventManager;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.tim.app.R;
import com.tim.app.RT;
import com.tim.app.constant.EventTag;
import com.tim.app.server.api.API_Statistics;
import com.tim.app.util.BitmapLoader;
import com.tim.app.util.ToastUtil;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.utils.SocializeUtils;


/**
 * @author fanxiaofeng
 * @date 2015-8-5
 * @Description 自定义分享
 */
public class CustomShareBoard extends PopupWindow implements OnClickListener {

    public enum ShareType {
        TEXT, IMAGE, RECORD, NIGHT_MODE, LINK, FONT
    }

    public enum ShareFrom {
        NORMAL, ARTICE, QUESTION, STORY, ANSWER, DYNAMIC
    }

    private Activity activity;
    private LinearLayout ll_bottom_action;
    private View vLine;
    private RelativeLayout rl_sina, rl_wechat, rl_wechat_circle, rl_qq, rl_qzone, rl_copy_link, rlAction, rl_font, rlDeleteTwo;
    private RelativeLayout rlReport, rlDelete, rlEdit;
    private UMShareUtil shareUtil;
    private String title, desc, descSina, descWX, imageUrl, smallImageUrl, bigImageUrl, targetUrl, videoUrl;
    private ShareType shareType;
    private ShareFrom shareFrom;
    private OnShareSuccessListener successListener;
    private Bitmap shareBitmap = null;
    private Bitmap shareBigBitmap = null;
    private Bitmap shareSmallBitmap = null;
    private LoadingDialog dialog;
    private TextView tvCancel;

    public CustomShareBoard(Activity activity, ShareFrom shareFrom) {
        super(activity);
        this.activity = activity;
        this.shareFrom = shareFrom;
        shareUtil = new UMShareUtil(activity, shareListener);
        dialog = new LoadingDialog(activity);
        dialog.setContent("");
        initView(activity);
    }


    private void initView(Context context) {
        View rootView = LayoutInflater.from(context).inflate(R.layout.share_custom_board, null);
        vLine = rootView.findViewById(R.id.vLine);
        ll_bottom_action = (LinearLayout) rootView.findViewById(R.id.ll_bottom_action);
        rl_sina = (RelativeLayout) rootView.findViewById(R.id.rl_sina);
        rl_wechat = (RelativeLayout) rootView.findViewById(R.id.rl_wechat);
        rl_wechat_circle = (RelativeLayout) rootView.findViewById(R.id.rl_wechat_circle);
        rl_qq = (RelativeLayout) rootView.findViewById(R.id.rl_qq);
        rl_qzone = (RelativeLayout) rootView.findViewById(R.id.rl_qzone);
        rl_copy_link = (RelativeLayout) rootView.findViewById(R.id.rl_copy_link);
        rlAction = (RelativeLayout) rootView.findViewById(R.id.rlAction);
        rlReport = (RelativeLayout) rootView.findViewById(R.id.rlReport);
        rlDelete = (RelativeLayout) rootView.findViewById(R.id.rlDelete);
        rlEdit = (RelativeLayout) rootView.findViewById(R.id.rlEdit);
        rl_font = (RelativeLayout) rootView.findViewById(R.id.rl_font);
        rlDeleteTwo = (RelativeLayout) rootView.findViewById(R.id.rlDeleteTwo);
        tvCancel = (TextView) rootView.findViewById(R.id.tvCancel);
        rl_font.setOnClickListener(this);
        rlDeleteTwo.setOnClickListener(this);
        rlEdit.setOnClickListener(this);
        rl_sina.setOnClickListener(this);
        rl_wechat.setOnClickListener(this);
        rl_wechat_circle.setOnClickListener(this);
        rl_qq.setOnClickListener(this);
        rl_qzone.setOnClickListener(this);
        rl_copy_link.setOnClickListener(this);
        rlReport.setOnClickListener(this);
        rlDelete.setOnClickListener(this);
        tvCancel.setOnClickListener(this);
        setContentView(rootView);
        setWidth(LayoutParams.MATCH_PARENT);
        setHeight(LayoutParams.WRAP_CONTENT);
        setFocusable(true);
        setBackgroundDrawable(new BitmapDrawable());
        setAnimationStyle(R.style.popupwindow_anim_style);
        setTouchable(true);

        if (shareFrom == ShareFrom.QUESTION) {
            ll_bottom_action.setVisibility(View.VISIBLE);
            vLine.setVisibility(View.VISIBLE);
        } else if (shareFrom == ShareFrom.STORY) {
            ll_bottom_action.setVisibility(View.VISIBLE);
            vLine.setVisibility(View.VISIBLE);
        } else if (shareFrom == ShareFrom.ARTICE) {
            ll_bottom_action.setVisibility(View.VISIBLE);
            vLine.setVisibility(View.VISIBLE);
        } else if (shareFrom == ShareFrom.ANSWER) {
            ll_bottom_action.setVisibility(View.VISIBLE);
            vLine.setVisibility(View.VISIBLE);
        } else if (shareFrom == ShareFrom.DYNAMIC) {
            ll_bottom_action.setVisibility(View.VISIBLE);
            vLine.setVisibility(View.VISIBLE);
        } else {
            ll_bottom_action.setVisibility(View.GONE);
            vLine.setVisibility(View.GONE);
        }
        rootView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
    }


    public void setDelete(boolean isDelete) {
        if (isDelete) {
            rlDelete.setVisibility(View.VISIBLE);
            rlReport.setVisibility(View.GONE);
        } else {
            rlDelete.setVisibility(View.GONE);
            rlReport.setVisibility(View.VISIBLE);
        }
        refreshUi();
    }

    public void setEidt(boolean isEdit, boolean isDelete) {
        if (isEdit) {
            rlDelete.setVisibility(View.GONE);
            rlReport.setVisibility(View.GONE);
            rlEdit.setVisibility(View.VISIBLE);
            if (isDelete) {
                rlDeleteTwo.setVisibility(View.VISIBLE);
            } else {
                rlDeleteTwo.setVisibility(View.INVISIBLE);
            }
        } else {
            rlDeleteTwo.setVisibility(View.INVISIBLE);
        }
        refreshUi();
    }

    private void refreshUi() {
        if (shareFrom == ShareFrom.QUESTION) {
            ll_bottom_action.setVisibility(View.VISIBLE);
            vLine.setVisibility(View.VISIBLE);
        } else if (shareFrom == ShareFrom.STORY) {
            ll_bottom_action.setVisibility(View.VISIBLE);
            vLine.setVisibility(View.VISIBLE);
        } else if (shareFrom == ShareFrom.ARTICE) {
            ll_bottom_action.setVisibility(View.VISIBLE);
            vLine.setVisibility(View.VISIBLE);
        } else if (shareFrom == ShareFrom.ANSWER) {
            ll_bottom_action.setVisibility(View.VISIBLE);
            vLine.setVisibility(View.VISIBLE);
        } else if (shareFrom == ShareFrom.DYNAMIC) {
            ll_bottom_action.setVisibility(View.VISIBLE);
            vLine.setVisibility(View.VISIBLE);
        } else {
            ll_bottom_action.setVisibility(View.GONE);
            vLine.setVisibility(View.GONE);
        }
    }

    @Override
    public void dismiss() {
        super.dismiss();
        backgroundAlpha(1f);
    }

    @Override
    public void onClick(View v) {
        SHARE_MEDIA platform = SHARE_MEDIA.WEIXIN;
        boolean isShare = false;
        int id = v.getId();
        switch (id) {
            case R.id.rl_sina:
                platform = SHARE_MEDIA.SINA;
                isShare = true;
                break;
            case R.id.rl_wechat:
                platform = SHARE_MEDIA.WEIXIN;
                isShare = true;
                break;
            case R.id.rl_wechat_circle:
                platform = SHARE_MEDIA.WEIXIN_CIRCLE;
                isShare = true;
                break;
            case R.id.rl_qq:
                platform = SHARE_MEDIA.QQ;
                isShare = true;
                break;
            case R.id.rl_qzone:
                platform = SHARE_MEDIA.QZONE;
                isShare = true;
                break;
            case R.id.rl_copy_link:
                int sdk = android.os.Build.VERSION.SDK_INT;
                if (sdk < 11) {
                    android.text.ClipboardManager clipboard = (android.text.ClipboardManager) activity.getSystemService(
                            Context.CLIPBOARD_SERVICE);
                    clipboard.setText(targetUrl.trim());
                } else {
                    android.content.ClipboardManager clipboard = (android.content.ClipboardManager) activity.getSystemService(
                            Context.CLIPBOARD_SERVICE);
                    android.content.ClipData clip = android.content.ClipData.newPlainText("", targetUrl.trim());
                    clipboard.setPrimaryClip(clip);
                }
                activity.runOnUiThread(
                        new Runnable() {
                            @Override
                            public void run() {
                                ToastUtil.showToast(RT.getString(R.string.copy_success));
                                dismiss();
                            }
                        });

                return;
            case R.id.rlReport:
                EventManager.ins().sendEvent(EventTag.DO_REPORT, 0, 0, null);
                activity.runOnUiThread(
                        new Runnable() {
                            @Override
                            public void run() {
                                dismiss();
                            }
                        });
                return;
            case R.id.rlDelete:
                EventManager.ins().sendEvent(EventTag.DO_CONTENT_DELETE, 0, 0, shareFrom);
                activity.runOnUiThread(
                        new Runnable() {
                            @Override
                            public void run() {
                                dismiss();
                            }
                        });
                return;
            case R.id.rlEdit:
                if (ShareFrom.QUESTION == shareFrom) {
                    EventManager.ins().sendEvent(EventTag.DO_EDIT_PROBLEM, 0, 0, null);
                } else {
                    EventManager.ins().sendEvent(EventTag.DO_EDIT_ANSWER, 0, 0, null);
                }
                activity.runOnUiThread(
                        new Runnable() {
                            @Override
                            public void run() {
                                dismiss();
                            }
                        });
                return;
            case R.id.rlDeleteTwo:
                EventManager.ins().sendEvent(EventTag.DO_CONTENT_DELETE, 0, 0, shareFrom);
                activity.runOnUiThread(
                        new Runnable() {
                            @Override
                            public void run() {
                                dismiss();
                            }
                        });
                return;
            case R.id.rl_font:
                EventManager.ins().sendEvent(EventTag.DO_SET_FONT, 0, 0, null);
                activity.runOnUiThread(
                        new Runnable() {
                            @Override
                            public void run() {
                                dismiss();
                            }
                        });
                return;
            case R.id.tvCancel:
                dismiss();
                break;
            default:
                break;
        }
        if (isShare) {
            if (platform == SHARE_MEDIA.WEIXIN || platform == SHARE_MEDIA.WEIXIN_CIRCLE) {
                if (!shareUtil.checkWXInstalled()) {
                    ToastUtil.showToast(RT.getString(R.string.share_uninstallWx));
                }
            }
            initShareInfo(platform);
            if (TextUtils.isEmpty(title)) {
                title = RT.getString(R.string.app_name);
            }
            DLOG.d("title==" + title);
            DLOG.d("desc==" + desc);
            DLOG.d("imageUrl==" + imageUrl);
            DLOG.d("targetUrl==" + targetUrl);

            if (TextUtils.isEmpty(targetUrl)) {
                targetUrl = "http://a.app.qq.com/o/simple.jsp?pkgname=com.moli.jasmine";
            }
            if (shareBitmap == null) {
                shareUtil.shareWeb(platform, title, desc, imageUrl, targetUrl);
            } else {
                shareUtil.shareWeb(platform, title, desc, shareBitmap, targetUrl);
            }
        }
    }


    /**
     * 分享图片链接
     *
     * @param title
     * @param desc
     * @param imageUrl
     * @param targetUrl
     */
    public void shareWeb(String title, String desc, String imageUrl, String targetUrl) {
        this.shareType = ShareType.LINK;
        this.title = title;
        this.desc = desc;
        this.imageUrl = imageUrl;
        this.targetUrl = targetUrl;
        showPopup();
    }

    public void shareWebWithBitmap(String title, String descSina, String descWX, Bitmap imageBitmap, String targetUrl) {
        this.shareType = ShareType.LINK;
        this.title = title;
        this.descSina = descSina;
        this.descWX = descWX;
        this.shareBitmap = imageBitmap;
        this.targetUrl = targetUrl;
        showPopup();
    }

    public void setShareInfo(String title, String desc, String descSina, String smallImageUrl, String bigImageUrl, String targetUrl) {
        this.title = title;
        this.desc = desc;
        this.descSina = descSina;
        this.imageUrl = bigImageUrl;
        this.smallImageUrl = smallImageUrl;
        this.bigImageUrl = bigImageUrl;
        this.targetUrl = targetUrl;

        BitmapLoader.ins().loadBitmap(bigImageUrl, R.drawable.ic_launcher, new SimpleImageLoadingListener() {
            @Override
            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                shareBigBitmap = loadedImage;
            }
        });
        BitmapLoader.ins().loadBitmap(smallImageUrl, R.drawable.ic_launcher, new SimpleImageLoadingListener() {
            @Override
            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                shareSmallBitmap = loadedImage;
            }
        });
//        showPopup();
    }

    public void showPopup() {
        this.showAtLocation(activity.getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
        backgroundAlpha(0.5f);
    }

    public void showPopup(boolean bgAlpha) {
        this.showAtLocation(activity.getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
        if (bgAlpha) {
            backgroundAlpha(0.5f);
        }
    }

    public interface OnShareSuccessListener {
        void onSuccess();
    }

    public void setOnShareSuccessListener(OnShareSuccessListener successListener) {
        this.successListener = successListener;
    }

    UMShareListener shareListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {
            SocializeUtils.safeShowDialog(dialog);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    SocializeUtils.safeCloseDialog(dialog);
                    CustomShareBoard.this.dismiss();
                }
            }, 3000);
        }

        @Override
        public void onResult(SHARE_MEDIA share_media) {
            SocializeUtils.safeCloseDialog(dialog);
            if (successListener != null) {
                successListener.onSuccess();
            }
            String type = "";
            if (share_media == SHARE_MEDIA.QQ || share_media == SHARE_MEDIA.QZONE) {
                type = "qq";
            } else if (share_media == SHARE_MEDIA.WEIXIN || share_media == SHARE_MEDIA.WEIXIN_CIRCLE) {
                type = "wx";
            } else if (share_media == SHARE_MEDIA.SINA) {
                type = "wb";
            }
            API_Statistics.ins().addShareData("", RT.application, type);
            activity.runOnUiThread(
                    new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.showToast(RT.getString(R.string.share_success));
                            CustomShareBoard.this.dismiss();
                        }
                    });
        }

        @Override
        public void onError(SHARE_MEDIA share_media, final Throwable throwable) {
            SocializeUtils.safeCloseDialog(dialog);
            activity.runOnUiThread(
                    new Runnable() {
                        @Override
                        public void run() {
                            throwable.printStackTrace();
                            ToastUtil.showToast(RT.getString(R.string.share_failed));
                            CustomShareBoard.this.dismiss();
                        }

                    });
        }

        @Override
        public void onCancel(SHARE_MEDIA share_media) {
            SocializeUtils.safeCloseDialog(dialog);
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ToastUtil.showToast(RT.getString(R.string.share_cancel));
                    CustomShareBoard.this.dismiss();
                }

            });
        }
    };

    private void initShareInfo(SHARE_MEDIA platform) {
        switch (platform) {
            case QQ:
                this.imageUrl = smallImageUrl;
                this.shareBitmap = shareBigBitmap;
                break;
            case QZONE:
                this.imageUrl = smallImageUrl;
                this.shareBitmap = shareBigBitmap;
                break;
            case SINA:
                this.imageUrl = bigImageUrl;
                this.shareBitmap = shareBigBitmap;
                this.desc = descSina;
                break;
            case WEIXIN:
                this.imageUrl = smallImageUrl;
                this.shareBitmap = shareSmallBitmap;
                break;
            case WEIXIN_CIRCLE:
                this.imageUrl = smallImageUrl;
                this.shareBitmap = shareSmallBitmap;
                break;
        }
    }

    public void closePopup() {
        super.dismiss();
    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        activity.getWindow().setAttributes(lp);
    }
}
